package cn.wit.summit.chwan.ui.activity;

import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableLinearLayout;
import com.github.aakira.expandablelayout.Utils;
import com.google.gson.Gson;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.DiscoveryChoiceListAdapter;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.ChoiceListBean;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.GameTypeBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.DiscoveryChoiceListRequest;
import cn.wit.summit.chwan.models.response.DiscoverChiceListResponse;
import cn.wit.summit.chwan.models.response.GameTypeListResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.TagGroup;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshFooter;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshHeader;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.constant.RefreshState;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnMultiPurposeListener;
import cn.wit.summit.chwan.widgets.refreshLayout.util.ScrollBoundaryUtil;
import retrofit2.Call;
import retrofit2.Retrofit;
import ru.noties.scrollable.CanScrollVerticallyDelegate;
import ru.noties.scrollable.OnFlingOverListener;
import ru.noties.scrollable.OnScrollChangedListener;
import ru.noties.scrollable.ScrollableLayout;

public class DiscoveryChoiceListActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.bar_title_tx)
    TextView           barTitleTx;
    @Bind(R.id.recyclerView)
    RecyclerView       recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    //        @Bind(R.id.scrollableLayout)
    ScrollableLayout scrollableLayout;
    @Bind(R.id.expandableLayout)
    ExpandableLinearLayout expandableLayout;
    @Bind(R.id.expandButton)
    View                   expandButton;
    @Bind(R.id.expandArrow)
    ImageView              expandArrow;
    @Bind(R.id.filters)
    TextView               filters;
    @Bind(R.id.filtersHolder)
    TextView               filtersHolder;

    @Bind(R.id.sortTagGroup)
    TagGroup     sortTagGroup;
    @Bind(R.id.tagTagGroup)
    TagGroup     tagTagGroup;
    @Bind(R.id.gameTagGroup)
    TagGroup     gameTagGroup;
    @Bind(R.id.appbar)
    AppBarLayout appbar;

    RecyclerView.LayoutManager layoutManager;
    private DiscoveryChoiceListAdapter adapter;

//    @Bind(R.id.mPtrFrame)
//    PtrClassicFrameLayout mPtrFrame;
//    XRecyclerView.LoadingListener loadingListener;

    //src
    List<ChoiceListBean> datas = new ArrayList<>();
    GameTypeListResponse gameTypeList;

    //viewBean
    List<DiscoveryChoiceListAdapter.ViewBean> viewBeans = new ArrayList<>();
    private String TAG = getClass().getSimpleName();

    private int initTag = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        customHeader = true;
        setContentView(R.layout.activity_discovery_choice_list);
        ButterKnife.bind(this);
        initApi();
        type = getIntent().getIntExtra("type", 0);
        String title = getIntent().getStringExtra("title");

        if (barTitleTx != null)
            barTitleTx.setText("专题");
        if (!TextUtils.isEmpty(title)) barTitleTx.setText(title);

        expandableLayout.setClosePosition(getResources().getDimensionPixelOffset(R.dimen.wdp225));
        expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {

            boolean init = false;

            @Override
            public void onPreOpen() {
                if (!init) {
                    init = true;
                    return;
                }
                createRotateAnimator(expandArrow, 0f, 180f).start();
            }

            @Override
            public void onPreClose() {
                createRotateAnimator(expandArrow, 180f, 0f).start();
            }

            public ObjectAnimator createRotateAnimator(final View target, final float from, final float to) {
                target.setPivotX(target.getWidth() / 2);
//                target.setPivotY(target.getHeight() / 2 - TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, target.getContext().getResources().getDisplayMetrics()));
                target.setPivotY(target.getHeight() / 2);

                ObjectAnimator animator = ObjectAnimator.ofFloat(target, "rotation", from, to);
                animator.setDuration(300);
                animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
                return animator;
            }
        });
//        expandableLayout.setExpanded(false);
        expandButton.setOnClickListener(this);
        initRecyclerView();
//        initScrollableLayout();

        appbar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            float ratio;
            Interpolator interpolator = new FastOutSlowInInterpolator();

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                int   scrollRange = appBarLayout.getTotalScrollRange();
                float fraction    = 1.f * (scrollRange + verticalOffset) / scrollRange;

                ratio = 1.f - fraction;
                ratio = interpolator.getInterpolation(ratio);
                filters.setAlpha(ratio);
                filtersHolder.setAlpha(ratio);

                if (ratio == 0) {
                    expandableLayout.setClickable(true);
                    expandButton.setClickable(true);
                } else {
                    expandableLayout.setClickable(false);
                    expandButton.setClickable(false);
                }
            }
        });

        showSkeleton();
        loadGameTypeList();
    }

    private void initScrollableLayout() {
        scrollableLayout.setCanScrollVerticallyDelegate(new CanScrollVerticallyDelegate() {
            @Override
            public boolean canScrollVertically(int direction) {
                LogUtils.e("direction = " + direction + " "
                        + ScrollBoundaryUtil.canScrollUp(recyclerView) + " "
                        + ScrollBoundaryUtil.canScrollDown(recyclerView));
                return recyclerView.canScrollVertically(direction);
            }
        });

        scrollableLayout.addOnScrollChangedListener(new OnScrollChangedListener() {
            float ratio;
            Interpolator interpolator = new FastOutSlowInInterpolator();

            @Override
            public void onScrollChanged(int y, int oldY, int maxY) {
                // we are showing background on the top for custom overScroll
                // we need to hide it accordingly
//                expandableLayout.setTranslationY(-y);

                final float mDistanceY;
                if (y < maxY) {
                    mDistanceY = .0F;
                } else {
                    mDistanceY = y - maxY;
                }
                expandableLayout.setTranslationY(mDistanceY);

                ratio = 1.f * y / maxY;
                ratio = interpolator.getInterpolation(ratio);
                filters.setAlpha(ratio);
                filtersHolder.setAlpha(ratio);

                if (ratio == 0) {
                    expandableLayout.setClickable(true);
                    expandButton.setClickable(true);
                } else {
                    expandableLayout.setClickable(false);
                    expandButton.setClickable(false);
                }
            }
        });

        scrollableLayout.setOnFlingOverListener(new OnFlingOverListener() {
            @Override
            public void onFlingOver(int y, long duration) {
                recyclerView.smoothScrollBy(0, y);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initRecyclerView() {
        adapter = new DiscoveryChoiceListAdapter(this, viewBeans);
//        recyclerView.addHeaderView();
//        recyclerView.addFooterView();
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
//        recyclerView.setIAdapter(adapter);
//        recyclerView.setOnRefreshListener(this);
//        recyclerView.setOnLoadMoreListener(this);
//        //刷新加载
//        recyclerView.post(new Runnable() {
//            @Override
//            public void run() {
//                recyclerView.setRefreshing(true);
//            }
//        });
//        recyclerView.addItemDecoration(new MyDecoration(this, getResources().getDrawable(R.drawable.special_game_divider), MyDecoration.VERTICAL_LIST));

        recyclerView.setAdapter(adapter);
        recyclerView.setFocusable(false);

        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                DiscoveryChoiceListActivity.this.onRefresh();
            }
        });
        refreshLayout.setOnLoadMoreListener(new cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                DiscoveryChoiceListActivity.this.onLoadMore();
            }
        });
        refreshLayout.setOnMultiPurposeListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderReleased(RefreshHeader header, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {

            }

            @Override
            public void onFooterMoving(RefreshFooter footer, boolean isDragging, float percent, int offset, int footerHeight, int maxDragHeight) {
                if (filtersHolder != null) {
                    if (offset > 0) {
                        filtersHolder.setVisibility(View.VISIBLE);
                    } else {
                        filtersHolder.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFooterReleased(RefreshFooter footer, int footerHeight, int maxDragHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int maxDragHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {

            }
        });
    }

    void loadGameTypeList() {
        api.getGameTypeList().enqueue(new MyCallback<ResponseBase<GameTypeListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<GameTypeListResponse> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }

            public void onResponse(GameTypeListResponse data) {
                try {
                    try {
                        PreferenceUtil.savePreference(DiscoveryChoiceListActivity.this, "game_type_list", new Gson().toJson(data));
                        gameTypeList = data;
                        notifyTagChanged();
                        initTag = 1;
                    } catch (Exception e) {
                        LogUtils.e(e.toString());
                    }

                    DiscoveryChoiceListActivity.this.onRefresh();
                    hideSkeleton();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(Exception e, int code) {
                try {
                    cancelLoadingError();
                    stopLoading();
                    if (e != null && !TextUtils.isEmpty(e.getMessage()))
                        showToast(e.getMessage());

                    hideSkeleton();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });
    }

    void notifyTagChanged() {
        removeHot();
        initGoogleTags();
        if (type == 6) {
            setTags(sortTagGroup, gameTypeList.getGg_sort_type(), 1);
            setTags(tagTagGroup, gameTypeList.getGg_tag_type(), 2);
        } else {
            setTags(sortTagGroup, gameTypeList.getSort_type(), 1);
            setTags(tagTagGroup, gameTypeList.getTag_type(), 2);
            setTags(gameTagGroup, gameTypeList.getGame_type(), 3);
        }

        if (expandableLayout != null)
            expandableLayout.initLayout();
//        expandableLayout.setClosePosition(getResources().getDimensionPixelOffset(R.dimen.wdp240));

        //calc expandable layout
        int closePosition = 0;
        int maxRow        = 3;
        int row           = 0;
        int itemHeight    = 0;
        int vSpacing      = getResources().getDimensionPixelOffset(R.dimen.wdp20);
        if (sortTagGroup != null && sortTagGroup.getChildCount() > 0) {
            if (itemHeight == 0)
                itemHeight = sortTagGroup.getChildAt(0).getMeasuredHeight() * sortTagGroup.getRowCount();
            row += sortTagGroup.getRowCount();
        }
        if (tagTagGroup != null && tagTagGroup.getChildCount() > 0) {
            if (itemHeight == 0)
                itemHeight = tagTagGroup.getChildAt(0).getMeasuredHeight() * tagTagGroup.getRowCount();
            row += tagTagGroup.getRowCount();
        }
        if (gameTagGroup != null && gameTagGroup.getChildCount() > 0) {
            if (itemHeight == 0)
                itemHeight = gameTagGroup.getChildAt(0).getMeasuredHeight() * gameTagGroup.getRowCount();
            row += gameTagGroup.getRowCount();
        }

        itemHeight = getResources().getDimensionPixelOffset(R.dimen.wdp53);

        if (expandableLayout != null) {
            if (row < maxRow) {
                if (row == 0) {
                    expandableLayout.setVisibility(View.GONE);
                    if (expandButton != null)
                        expandButton.setVisibility(View.GONE);
                } else {
                    closePosition = (vSpacing + itemHeight) * row + vSpacing;
                    expandableLayout.setClosePosition(closePosition);
                    if (expandArrow != null)
                        expandArrow.setVisibility(View.INVISIBLE);
                }
            } else {
                closePosition = (vSpacing + itemHeight) * maxRow + vSpacing;
                expandableLayout.setClosePosition(closePosition);
            }

            expandableLayout.move(closePosition, 0, null);
        }
    }

    private void removeHot() {
        if (gameTypeList.getGg_sort_type() != null && gameTypeList.getGg_sort_type().size() > 0) {
            for (int i = 0; i < gameTypeList.getGg_sort_type().size(); i++) {
                if (gameTypeList.getGg_sort_type().get(i).getSort_type_id() == 3
                        || ((!TextUtils.isEmpty(gameTypeList.getGg_sort_type().get(i).getSort_type_name())) && gameTypeList.getGg_sort_type().get(i).getSort_type_name().equals("最热"))) {
                    gameTypeList.getGg_sort_type().remove(i);
                    break;
                }
            }
        }
        if (gameTypeList.getSort_type() != null && gameTypeList.getSort_type().size() > 0) {
            for (int i = 0; i < gameTypeList.getSort_type().size(); i++) {
                if (gameTypeList.getSort_type().get(i).getSort_type_id() == 3
                        || ((!TextUtils.isEmpty(gameTypeList.getSort_type().get(i).getSort_type_name())) && gameTypeList.getSort_type().get(i).getSort_type_name().equals("最热"))) {
                    gameTypeList.getSort_type().remove(i);
                    break;
                }
            }
        }
    }

    void setTags(final TagGroup tagGroup, final List<GameTypeBean> gameTypeBeans, final int tagType) {
        if (gameTypeBeans == null || tagGroup == null) return;
        if (gameTypeBeans.size() < 1) {
            tagGroup.setVisibility(View.GONE);
            return;
        }
        tagGroup.setVisibility(View.VISIBLE);
        final List<String> tags = new ArrayList<>();
        for (int i = 0; i < gameTypeBeans.size(); i++) {
            String name = "";
            if (tagType == 1) name = gameTypeBeans.get(i).getSort_type_name();
            else if (tagType == 2) name = gameTypeBeans.get(i).getTag_type_name();
            else if (tagType == 3) name = gameTypeBeans.get(i).getGame_type_name();
            tags.add(name);
        }
        if (tags.size() < 1) {
            tagGroup.setVisibility(View.GONE);
            return;
        }
        if (tagType != 1)
            tags.add(0, "全部");
        tagGroup.setTags(tags);
        tagGroup.setOnTagClickListener(new TagGroup.OnTagClickListener() {
            GameTypeBean bean;

            @Override
            public void onTagClick(String tag) {
                try {
                    if (loading == 1) return;//刷新期间阻止快速点击
                    int pos = tags.indexOf(tag);

                    if (tagType == 1) {
                        if (pos < 0 || pos > gameTypeBeans.size() - 1) return;
                        bean = gameTypeBeans.get(pos);
                        sort_type = bean.getSort_type_id();
                        sort_name = bean.getSort_type_name();
                    } else if (tagType == 2) {
                        if (pos == 0) {
                            tag_type = 0;
                            tag_name = tag;
                        } else {
                            int index = pos - 1;
                            if (index < 0 || index > gameTypeBeans.size() - 1) return;
                            bean = gameTypeBeans.get(index);
                            tag_type = bean.getTag_type_id();
                            tag_name = bean.getTag_type_name();
                        }
                    } else if (tagType == 3) {
                        if (pos == 0) {
                            game_type = 0;
                            game_name = tag;
                        } else {
                            int index = pos - 1;
                            if (index < 0 || index > gameTypeBeans.size() - 1) return;
                            bean = gameTypeBeans.get(index);
                            game_type = bean.getGame_type_id();
                            game_name = bean.getGame_type_name();
                        }
                    }
                    tagGroup.setChecked(pos, true);
                    sortCheck(pos);

                    String tags = "";
                    tags += (TextUtils.isEmpty(sort_name) ? "" : sort_name + " · ");
                    tags += (TextUtils.isEmpty(tag_name) || tag_name.equals("全部") ? "" : tag_name + " · ");
                    tags += (TextUtils.isEmpty(game_name) || game_name.equals("全部") ? "" : game_name + " · ");
                    tags = tags.substring(0, tags.length() - (" · ").length());
                    filters.setText(tags);
                    filtersHolder.setText(tags);

                    if (initTag == 1)
                        onRefresh();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            void sortCheck(int position) {
                int                hotIndex    = 0;
                int                choiceIndex = 0;
                List<GameTypeBean> sort_types  = gameTypeList.getSort_type();
                List<GameTypeBean> tag_types   = gameTypeList.getTag_type();
                if (type == 6) {
                    sort_types = gameTypeList.getGg_sort_type();
                    tag_types = gameTypeList.getGg_tag_type();
                }
                for (int i = 0; i < sort_types.size(); i++) {
                    if (sort_types.get(i).getSort_type_id() == 2) hotIndex = i;//最新
                    else if (sort_types.get(i).getSort_type_id() == 1)//精选
                        choiceIndex = i;
                }

//                if (type != 6) {
                if (tagType == 2 || tagType == 3) {
                    if (position != 0 && sortTagGroup.getCheckedIndex() == choiceIndex) {
                        sort_type = sort_types.get(hotIndex).getSort_type_id();
                        sort_name = sort_types.get(hotIndex).getSort_type_name();
                        sortTagGroup.setChecked(hotIndex, true);
                    }
                } else if (tagType == 1) {
                    if (position == choiceIndex && tagTagGroup.getCheckedIndex() != 0
                            && tag_types != null
                            && tag_types.size() > 0
                            ) {
                        tag_type = 0;
                        tag_name = (tagTagGroup.getTags() != null && tagTagGroup.getTags().length > 0) ? tagTagGroup.getTags()[0] : "";
                        tagTagGroup.setChecked(0, true);
                    }
                    if (position == choiceIndex && gameTagGroup.getCheckedIndex() != 0
                            && gameTypeList.getGame_type() != null
                            && gameTypeList.getGame_type().size() > 0
                            ) {
                        game_type = 0;
                        game_name = (gameTagGroup.getTags() != null && gameTagGroup.getTags().length > 0) ? gameTagGroup.getTags()[0] : "";
                        gameTagGroup.setChecked(0, true);
                    }
                }
//                }
            }
        });

        try {
            if (tagGroup.getChildAt(0) != null) {
                tagGroup.getChildAt(0).performClick();
            }
//            tagGroup.requestLayout();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e(TAG, tagType + " tag lineCount=" + tagGroup.getRowCount() + " measuredHeight=" + tagGroup.getMeasuredHeight());
    }

    //region loadSvr
    int loading   = 0;
    int type      = 0;// (1 破解 2 网游 3 中文汉化 4 大型单机 5 苹果专区 6 谷歌专区)
    int sort_type = 0, tag_type = 0, game_type = 0;
    String sort_name = "", tag_name = "", game_name = "";
    int pn = 1, pc = 20;

    //    sort_type=1&tag_type=26&game_type=18&pn=1&pc=10
    void loadSvr() {
        loading = 1;
        if (type == 6) {//谷歌专区
            if (sort_type == 1) {//精选
                getChoiceList();//精选
            } else {//最新、排行
                getRankingByGgArea();//最新、最热、排行
            }
        } else if (type == 5) {//苹果专区
            if (sort_type == 2 || sort_type == 3) {
                getGameListByApple();//最新、最热
            } else {
                getChoiceList();//精选
            }
        } else {
            if (sort_type == 2 || sort_type == 3) {
                getGameListByArea();//最新、最热
            } else {
                getChoiceList();//精选
            }
        }
    }

    void getGameListByArea() {// 1 破解 2 网游 3 中文汉化 4 大型单机
        getHotNewGameList();
    }

    void getGameListByApple() {//苹果专区
        getHotNewGameList();
    }

    void getHotNewGameList() {
        DiscoveryChoiceListRequest request = retrofitManager.getHotNewGameList(type, sort_type, tag_type, game_type, pn, pc);
        Call<ResponseBase<List<GameListBaseBean>>>                       call    = null;
        if (type == 6)//google
        {
            call = api.getRankingByGgArea(request);
        } else if (type == 5)//apple
        {
            call = api.getGameListByAppleArea(request);
        } else {
            call = api.getGameListByArea(request);
        }
        call.enqueue(new MyCallback<ResponseBase<List<GameListBaseBean>>>() {
            @Override
            public void onSuccess(ResponseBase<List<GameListBaseBean>> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }
//        OkHttpUtil.getDefault(this).doPostAsync(BuildRequestUtils.getInstance(this).getHotNewGameList(type, sort_type, tag_type, game_type, pn, pc)
//                , new NetCallBack<>(this, GameListBaseBean.class, new NetCallBack.Back<List<GameListBaseBean>>() {//ResponseBase<List<TopAdBean>>
//
//                    @Override
//                    public void onCache(List<GameListBaseBean> data) {
////                        addGoogleViewDatas(data);
////                        adapter.notifyDataSetChanged();
//                    }

            public void onResponse(List<GameListBaseBean> data) {
                cancelLoadingFinish();
                if (pn == 1) {
                    viewBeans.clear();
                    datas.clear();
                }
                addGoogleViewDatas(data);
                if (data == null || data.size() == 0) {
                    stopLoading(true);
                } else {
                    pn++;
                    stopLoading();
                    if (pn == 2 && refreshLayout!=null && refreshLayout.getLayout()!=null) {
                        refreshLayout.getLayout().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!ScrollBoundaryUtil.canScrollDown(recyclerView)) {
                                    onLoadMore();
                                }
                            }
                        },20);
                    }
                }

            }

            public void onFailure(Exception e, int code) {
                cancelLoadingError();
                stopLoading();
                showToast(e.getMessage());
            }
        });
    }

    //region 谷歌专区
    void initGoogleTags() {
//        if (type != 6) return;
//        if (gameTypeList == null || gameTypeList.getSort_type() == null || gameTypeList.getSort_type().size() == 0)
//            return;
//
//        gameTypeList.getGame_type().clear();
//
//        //排序
//        gameTypeList.getSort_type().clear();
//        SparseArray<GameTypeBean> sortTypes = new SparseArray<>();
//        sortTypes.append(1, new GameTypeBean().setSortType(1, "精选"));//精选
//        sortTypes.append(0, new GameTypeBean().setSortType(3, "排行"));//最热 -> 排行
//        sortTypes.append(2, new GameTypeBean().setSortType(2, "最新"));//最新
//        for (int i = 0; i < sortTypes.size(); i++) {
//            gameTypeList.getSort_type().add(sortTypes.get(i));
//        }
////        for (GameTypeBean bean :
////                gameTypeList.getSort_type()) {
////            if (bean.getSort_type_id() == 1) bean.setSort_type_name("排行");
////        }
//
//        //地区筛选
//        gameTypeList.getTag_type().clear();
//        SparseArray<String> areaTypes = new SparseArray<>();
//        areaTypes.append(1, "日本");
//        areaTypes.append(2, "韩国");
//        areaTypes.append(3, "美国");
//        areaTypes.append(4, "其他");
//        for (int i = 1; i <= areaTypes.size(); i++) {
//            GameTypeBean areaType = new GameTypeBean();
//            areaType.setTag_type_id(i);
//            areaType.setTag_type_name(areaTypes.get(i));
//            gameTypeList.getTag_type().add(areaType);
//        }
    }

    void getRankingByGgArea() {//谷歌专区
        getHotNewGameList();
    }

    void addGoogleViewDatas(List<GameListBaseBean> data) {
        if (data == null) return;
        for (int i = 0; i < data.size(); i++) {
            viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.GameItem.ordinal(),
                    data.get(i)));
        }
    }
    //endregion

    void getChoiceList() {
        DiscoveryChoiceListRequest request = retrofitManager.getChoiceListRequest(type, sort_type, tag_type, game_type, pn, pc);
        api.getChoiceList(request).enqueue(new MyCallback<ResponseBase<DiscoverChiceListResponse>>() {
            @Override
            public void onSuccess(ResponseBase<DiscoverChiceListResponse> model) {
                if (model != null) {
                    if (model.getCode() == 600)
                        onResponse(model.getData_info());
                    else
                        onFailure(model.getCode(), model.getMsg());
                } else {
                    onFailure(-1, "服务器数据为空！");
                }

            }

            @Override
            public void onFailure(int code, String msg) {
                onFailure(new Exception(msg), code);
            }

            public void onResponse(DiscoverChiceListResponse data) {
                cancelLoadingFinish();
                if (pn == 1) {
                    viewBeans.clear();
                    datas.clear();
                }
                if (data != null) {
                    if (pn == 1) {
                        addViewDatas(data.getFirst_list());
                    }
                    addViewDatas(data.getSecond_list());
                }
                if (data == null ||
                        (pn == 1 && (data.getFirst_list() == null || data.getFirst_list().size() == 0)) ||
                        (pn > 1 && (data.getSecond_list() == null || data.getSecond_list().size() == 0))
                        ) {
                    stopLoading(true);
                } else {
                    pn++;
                    stopLoading();
                    if (pn == 2 && refreshLayout!=null && refreshLayout.getLayout()!=null) {
                        refreshLayout.getLayout().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (!ScrollBoundaryUtil.canScrollDown(recyclerView)) {
                                    onLoadMore();
                                }
                            }
                        },10);
                    }
                }

            }

            public void onFailure(Exception e, int code) {
                cancelLoadingError();
                stopLoading();
                showToast(e.getMessage());
            }
        });

    }

    void addViewDatas(List<ChoiceListBean> data) {
        if (data == null) return;
        datas.addAll(data);
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getJump_show_type() == 2
                    && data.get(i).getJump_ad_switch() == 1) {//广告位
                viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.AdPic.ordinal(),
                        (JumpBaseBean) data.get(i)));
            } else if (data.get(i).getJump_show_type() == 1
                    && data.get(i).getGame_list() != null
                    && data.get(i).getGame_list().size() > 0) {//游戏列表
                viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.Title.ordinal(),
                        (JumpBaseBean) data.get(i)));
                for (int j = 0; j < (data.get(i).getGame_list() != null ? data.get(i).getGame_list().size() : 0); j++) {
                    viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.GameItem.ordinal(),
                            data.get(i).getGame_list().get(j)));
                }
            } else if (data.get(i).getJump_show_type() == 3) {//精选专题
                viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.Title.ordinal(),
                        (JumpBaseBean) data.get(i)));
                for (int j = 0; j < (data.get(i).getData_list() != null ? data.get(i).getData_list().size() : 0); j++) {
                    if (data.get(i).getData_list().get(j).getJump_ad_switch() == 1)
                        viewBeans.add(new DiscoveryChoiceListAdapter.ViewBean(DiscoveryChoiceListAdapter.ViewType.ChoicePic.ordinal(),
                                data.get(i).getData_list().get(j)));
                }
            }
        }
    }

    private void stopLoading(boolean noMore) {
            loading = 0;
            adapter.clearDownloadStatus();
            adapter.notifyDataSetChanged();
            stopXlistRefreshAndLoadMore(noMore);
    }

    private void stopLoading() {
        stopLoading(false);
    }

    void stopXlistRefreshAndLoadMore(final boolean noMore) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            if (noMore) refreshLayout.finishLoadMoreWithNoMoreData();
            else refreshLayout.finishLoadMore();
        }
    }

    public void onRefresh() {
        refreshLayout.setNoMoreData(false);
        pn = 1;
        if (initTag != 1) {
            loadGameTypeList();
        } else
            loadSvr();
    }

    public void onLoadMore() {
        loadSvr();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.expandButton) {
            expandableLayout.toggle();
        }
    }

    //endregion


    @OnClick(R.id.back)
    void back() {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!TextUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View         view     = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }

        super.onEventMainThread(downloadEvent);
    }

    @Override
    public void reGetData() {
        if (NetWorkUtils.isNetworkConnected(this))
            onRefresh();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_discovery_choice_list_skeleton;
    }


    //region Retrofit
    private RetrofitManager retrofitManager;
    private Retrofit        retrofit;
    private ApiUtil         api;

    void initApi() {
        if (retrofitManager == null) {
            retrofitManager = RetrofitManager.getInstance(this);
            retrofit = retrofitManager.getRetrofit();
            api = retrofit.create(ApiUtil.class);
        }
    }
    //endregion
}
